// index.js
import * as selectData from "../select/selectdata.js"
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
const select = function(dataArray) {
  if (dataArray.length === 0) {  
    return 0; 
  }  
  const randomIndex = Math.floor(Math.random() * dataArray.length);  
  const selectedObject = dataArray[randomIndex]; 
  return selectedObject;  
};
const fs = wx.getFileSystemManager()
const LETTER_NUM_TO_KBD_NUM = new Map([
  [0, 10],
  [1, 23],
  [2, 21],
  [3, 12],
  [4, 2],
  [5, 13],
  [6, 14],
  [7, 15],
  [8, 7],
  [9, 16],
  [10, 17],
  [11, 18],
  [12, 25],
  [13, 24],
  [14, 8],
  [15, 9],
  [16, 0],
  [17, 3],
  [18, 11],
  [19, 4],
  [20, 6],
  [21, 22],
  [22, 1],
  [23, 20],
  [24, 5],
  [25, 19]
])
let valid_words;
fs.readFile({
  filePath: `词库/sorted_words.json`,
  encoding: 'utf8',
  position: 0,
  success(res) {
    console.log(res)
    valid_words = res.data.split(/\s+/)
    console.log(valid_words)
  },
  fail(res) {
    console.error(res)
  }
})
Page({
  data: {
    wordToGuess : "",
    wordLength : 5,
    guessChance : 6,
    curLine : 0,
    curCol : 0,
    submitted : Array.from({length:6},()=>Array(5).fill("")),
    checkstatus: Array.from({length:6},()=>Array(5).fill("")),
    right_str:"right",
    wrong_str:"wrong",
    no_str:"",
    gamestate: 0,
    isFlipped: Array.from({ length: 6 }, () => Array(5).fill(false)),
    isError: Array.from({ length: 6 }, () => Array(5).fill(false)),
    level: "",
    //sequence on keyboard, allows 0 ~ 3 only
    //white:0, grey:1, yellow:2, green:3
    stage:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    allowInput: true,

    /* 调试用消息输出按钮 */
    isSuccess: false,
    isFailure: false,
    isInvalidInput: false,
    isVisible: false,

    score: 0,
  },
  onLoad: function(e) {
    console.log(e.level)
    this.setData({
      wordToGuess: e.id.trim(),
      level: e.level.trim(),
    })
  },

/* 调试用消息输出按钮start */
  triggerSuccessMessage: function() {
    this.setData({
      //isSuccess: false,
      //isInvalidInput: true,
      isSuccess: true,
      isFailure: false,
    });
  },

  triggerInvalidInputMessage: function() {
    this.setData({
      isSuccess: false,
      isFailure: true,
    });
  },

  

/* 调试用消息输出按钮end */

/* 弹窗关闭按钮start */
closeModal() {
  this.setData({
    isSuccess: false,
    isFailure: false,
  });
},
/* 弹窗关闭按钮end */

  goBackToMain: function(e) {
    wx.navigateTo({
      url: '/pages/select/select',
    });
  },
  nextGame: function() {
    let nextword;
    let level = this.data.level;
    if(level==="gaokao"){
      nextword=select(selectData.datagaokao).word;
    } else if(level==="siji"){
      nextword=select(selectData.datasiji).word;
    } else{
      nextword=select(selectData.dataliuji).word;
    }
    this.setData({
      wordToGuess: nextword,
      curLine : 0,
      curCol : 0,
      submitted : Array.from({length:6},()=>Array(5).fill("")),
      checkstatus: Array.from({length:6},()=>Array(5).fill("")),
      right_str:"right",
      wrong_str:"wrong",
      no_str:"",
      gamestate: 0,
      isFlipped: Array.from({ length: 6 }, () => Array(5).fill(false)),
      isError: Array.from({ length: 6 }, () => Array(5).fill(false)),
      //sequence on keyboard, allows 0 ~ 3 only
      //white:0, grey:1, yellow:2, green:3
      stage:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
      allowInput: true,
    /* 调试用消息输出按钮 */
      isSuccess: false,
      isFailure: false,
      isInvalidInput: false,
      score: this.data.score + (level==='gaokao'?50:level==='siji'?100:level==='liuji'?150:0)
    });
  },
  restart:function(){
    let nextword;
    let level = this.data.level;
    if(level==="gaokao"){
      nextword=select(selectData.datagaokao).word;
    } else if(level==="siji"){
      nextword=select(selectData.datasiji).word;
    } else{
      nextword=select(selectData.dataliuji).word;
    }
    console.log(nextword)
    this.setData({
      wordToGuess: nextword,
      curLine : 0,
      curCol : 0,
      submitted : Array.from({length:6},()=>Array(5).fill("")),
      checkstatus: Array.from({length:6},()=>Array(5).fill("")),
      no_str:"",
      gamestate: 0,
      isFlipped: Array.from({ length: 6 }, () => Array(5).fill(false)),
      isError: Array.from({ length: 6 }, () => Array(5).fill(false)),
      //sequence on keyboard, allows 0 ~ 3 only
      //white:0, grey:1, yellow:2, green:3
      stage:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
      allowInput: true,
    /* 调试用消息输出按钮 */
      isSuccess: false,
      isFailure: false,
      isInvalidInput: false,
      score: 0
    });
    console.log(this.data)
  },
  checkValidWord: function(nextsubmitword) {
    
    let s="";
    for(let c of nextsubmitword) {
      s += c;
    }
    console.log(valid_words.indexOf(s.toLowerCase()));
    if(valid_words.indexOf(s.toLowerCase())>=0){
      console.log("true")
      return true;
    } else {
      return false;
    }
  },
  updateIsFlipped: function(curLine, curCol, newIsFlipped){
    if(curCol == this.data.wordLength - 1){
      for(let j = 0; j < this.data.wordLength; j++){
        newIsFlipped[curLine][j] = true;
      }
    }
    return newIsFlipped;
  },
  checkRightWord: function(submitWord) {
    let s="";
    for(let c of submitWord){
      s+=c;
    }
    s=s.toLowerCase();
    console.log(s);
    console.log(this.data.wordToGuess);
    if(this.data.wordToGuess === s){
      return true;
    } else {
      return false;
    }
  },
  updateCheckStatus: function(submitLine, submitWord, newcheckstatus){
    let lowerSubmitWord = new Array();
    for(let ch of submitWord){
      lowerSubmitWord.push(ch.toLowerCase());
    }
    let word = this.data.wordToGuess;
    let cnt = new Map();
    for(let i = 0; i < this.data.wordLength; i ++){
      if(cnt.has(word[i])){
        let cur = cnt.get(word[i]);
        cnt.set(word[i], cur + 1);
      } else {
        cnt.set(word[i], 1);
      }
    }
    for(let j = 0; j < this.data.wordLength; j ++){
      if(word[j] == lowerSubmitWord[j]){
        newcheckstatus[submitLine][j] = "right";
        let cur = cnt.get(word[j]);
        cnt.set(word[j], cur - 1);
      } 
    }
    for(let j = 0; j < this.data.wordLength; j ++){
      if(word[j] == lowerSubmitWord[j]){
        continue;
      }
      if(cnt.has(lowerSubmitWord[j])){
        if(cnt.get(lowerSubmitWord[j]) > 0){
          let cur = cnt.get(lowerSubmitWord[j]);
          cnt.set(lowerSubmitWord[j], cur - 1);
          newcheckstatus[submitLine][j] = "pos_wrong";
        } else {
          newcheckstatus[submitLine][j] = "wrong";
        }
      } else {
        newcheckstatus[submitLine][j] = "wrong";
      }
    }
    return newcheckstatus;
  },
  ontap: function(e){ // 响应虚拟键盘的点击事件
    console.log(this.data.submitted[0]===this.data.submitted[1]);
    for(let a of this.data.submitted){
      for(let b of a){
        console.log(b)
      }
    }
    if(!this.data.allowInput){
      return;
    }
    console.log(e);
    let id = e.target.id;
    let inputc;
    if(id.startsWith("kbd-")){
      inputc = id.split("-")[1];
    } else {
      return;
    }
    console.log(this.data.submitted)
    // console.log(inputc);
    let nextSubmitState = this.data.submitted;
    let newstage = this.data.stage;
    let newcheckstatus = this.data.checkstatus;
    let curline = this.data.curLine;
    let curcol = this.data.curCol;
    let newIsFlipped = this.data.isFlipped;
    let new_isError = this.data.isError;
    let new_gamestate = this.data.gamestate;
    let nextcol = curcol;
    let nextline = curline;
    let new_isinvalid = false;
    let new_allowinput = true;
    if(inputc==="backspace"){
      if(curcol > 0){
        nextSubmitState[curline][curcol - 1] = "";
        nextcol --;
      }
      console.log(nextSubmitState[curline])
      console.log(nextcol)
    } else {
      console.log(nextSubmitState)
      nextSubmitState[curline][curcol] = inputc.toUpperCase();
      console.log(nextSubmitState)
      if(curcol < this.data.wordLength - 1) {
        nextcol ++;
      } else {
        if(this.checkValidWord(nextSubmitState[curline])){
          newIsFlipped = this.updateIsFlipped(curline, curcol, newIsFlipped);
          newstage = this.updateKbdStage(nextSubmitState[curline], newstage);
          newcheckstatus = this.updateCheckStatus(curline, nextSubmitState[curline], newcheckstatus);
          // console.log(newstage);
          nextcol = 0;
          if(this.checkRightWord(nextSubmitState[curline])){
            new_allowinput = false;
            setTimeout(() => {
              this.setData({
                isSuccess: true
              })
            }, 1000);
          } else {
            if(curline < this.data.guessChance - 1){
              nextline ++;
            } else {
              new_allowinput = false;
              setTimeout(() => {
                this.setData({
                  isFailure: true
                });
              }, 1000);
            }
          }
        } else {
          for(let i = 0; i < this.data.wordLength; i++){
            new_isError[curline][i] = true;
          }
          new_allowinput = false;
          new_isinvalid = true;
          
          setTimeout(() => {
            let new_isError = this.data.isError;
            let new_submitState = this.data.submitted;
            for(let i = 0; i < this.data.wordLength; i++){
              new_isError[curline][i] = false;
              new_submitState[curline][i] = "";
            }
            console.log("change again")
            this.setData({
              allowInput: true,
              isError: new_isError,
              submitted: new_submitState,
              curCol: 0
            });
          }, 1000);
        }
      }
    }
    this.setData({
      allowInput: new_allowinput,
      isInvalidInput: new_isinvalid,
      isFlipped: newIsFlipped,
      submitted: nextSubmitState,
      isError: new_isError,
      gamestate: new_gamestate,
      checkstatus: newcheckstatus,
      stage: newstage,
      curLine: nextline,
      curCol: nextcol
    })
    if(this.data.isInvalidInput){
      this.setData({
        isVisible: true
      })
    }
  },
  updateKbdStage: function(submitWord, newstage) {
    let word = this.data.wordToGuess;
    for(let j = 0; j < this.data.wordLength; j ++){
      let newstatus = 1;
      if(submitWord[j].toLowerCase() == word[j]){
        newstatus = 3;
      } else {
        if(word.indexOf(submitWord[j].toLowerCase()) >= 0){
          newstatus = 2;
        } else {
          newstatus = 1;
        }
      }
      let kbdnum = LETTER_NUM_TO_KBD_NUM.get(submitWord[j].charCodeAt(0) - 65);
      newstage[kbdnum] = newstatus > newstage[kbdnum] ? newstatus : newstage[kbdnum];
    }
    return newstage;
  },
})








